package com.woniuxy.crm.unilt;

import com.woniuxy.crm.Mapper.CategoryMapper;
import com.woniuxy.crm.Mapper.ProductMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;


@Slf4j
public class MyBatisUtil {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        // 读取配置文件
        String resource = "mybatis-config.xml";
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

    }

    // ThreadLocal保证存储在其中的数据在一次操作中是独一份
    private static ThreadLocal<SqlSession> sessions = new ThreadLocal<>();

    public static SqlSession getSqlSession() {
        SqlSession sqlSession = sessions.get();
        if (sqlSession == null) {
            sqlSession = sqlSessionFactory.openSession();
            sessions.set(sqlSession);
        }
        log.debug("sqlSession:{}", sqlSession);
        return sqlSession;
    }

    public static <T> T getMapper(Class<T> c) {
        return getSqlSession().getMapper(c);
    }
}